import {Button, Form, message, Modal, Tabs, Tag} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm, ProFormSelect, ProFormSwitch,
  ProFormText
} from '@ant-design/pro-form';
import {isSuccess} from "@/utils/utils";
import {Label} from "@/services/api-functions";
import 'braft-editor/dist/index.css'
import {LabelAdd} from "@/services/api-types";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";

const handleEdit = async (fields: any, labelType: string) => {
  try {
    const rpo: LabelAdd = {
      labelName: fields.labelName??'',
      enabling: fields.enabling ? 1: 0,
      labelType
    }
    if (isSuccess(((await Label.labelAdd(rpo))?.code))) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

const handlePublishStatus = async (select: any, enabling: number) => {
  if (!select) return true;
  try {
    if (isSuccess((await Label.labelMod({id: select.id, enabling}))?.code)) {
      message.success(enabling ? '上架成功' : '下架成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};


const LabelList: React.FC<any> = () => {

  const [formRef] = Form.useForm()
  const [visible, handleVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [active, setActive] = useState<'RESOURCES'|'ARTICLE'|'WORKS'>('RESOURCES')

  const columns: ProColumns[] = [
    {
      title: '名称',
      dataIndex: 'labelName',
      ellipsis: true,
      fixed: 'left'
    },
    {
      title: '创建者',
      dataIndex: 'createUserNickName',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '是否启用',
      dataIndex: 'enabling',
      width: 150,
      hideInSearch: true,
      ellipsis: true,
      render: (_, record) => record.enabling == '1' ? '已启用' : '未启用'
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      width: 250,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        record.enabling == '1'
          ? <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要禁用 <Tag color='#108ee9'>{record.labelName}</Tag> 吗？</span>,
            okText: '禁用',
            cancelText: '取消',
            onOk: async () => {
              if (await handlePublishStatus(record, 0)) {
                actionRef.current?.reload()
              }
            },
          })}>禁用</a>
          : <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要启用 <Tag color='#108ee9'>{record.labelName}</Tag> 吗？</span>,
            okText: '确定要启用',
            cancelText: '取消',
            onOk: async () => {
              if (await handlePublishStatus(record, 1)) {
                actionRef.current?.reload()
              }
            },
          })}>启用</a>
      ],
    },
  ];

  const renderList = (labelType: 'RESOURCES'|'ARTICLE'|'WORKS') => {
    return <ProTable<any, any>
      headerTitle='标签列表'
      actionRef={actionRef}
      rowKey="id"
      search={{labelWidth: 120,}}
      toolBarRender={() => [
        <Button
          type="primary"
          key="primary"
          onClick={() => {handleVisible(true);}}>
          <PlusOutlined/> 添加标签
        </Button>,
      ]}
      request={async (params) => {

        const {data: {data, total}, code}: any = await Label.page({...params, labelType});

        return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
      }}
      columns={columns}
      scroll={{ x: 1300 }}
    />
  }

  return (
    <PageContainer>
      <Tabs activeKey={active} onChange={(activeKey: any) => setActive(activeKey)}>
        <Tabs.TabPane key='RESOURCES' tab='资源'>
          {
            renderList('RESOURCES')
          }
        </Tabs.TabPane>
        <Tabs.TabPane key='ARTICLE' tab='文章'>
          {
            renderList('ARTICLE')
          }
        </Tabs.TabPane>
        <Tabs.TabPane key='WORKS' tab='作品'>
          {
            renderList('WORKS')
          }
        </Tabs.TabPane>

      </Tabs>

      <ModalForm
        title={`添加标签`}
        width="750px"
        form={formRef}
        visible={visible}
        onVisibleChange={v => {
          handleVisible(v)
          if (!v) {
            formRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await handleEdit(value as any, active)) {
            handleVisible(false);
            formRef?.resetFields()
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText label='标签名称' required rules={[{required: true, message: '请填写标签名称',},]} name="labelName"/>
        <ProFormSelect label='分类' required name='labelType' initialValue={active} disabled options={[
          {label: '资源', value: 'RESOURCES'},
          {label: '文章', value: 'ARTICLE'},
          {label: '作品', value: 'WORKS'},
        ]}/>
        <ProFormSwitch label='是否启用' unCheckedChildren='不启用' checkedChildren='启用' initialValue={true} name='enabling' required/>
      </ModalForm>
    </PageContainer>
  );
};

export default LabelList;
